package com.cc.AOP;

import com.cc.mapper.OperateLogMapper;

import com.cc.pojo.OperateLog;
import com.cc.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint joinPoint ,LogOperation log) throws Throwable {
        //记录开始时间
        long begin=System.currentTimeMillis();
        //执行方法
        Object result=joinPoint.proceed();
        //当前时间
        long end= System.currentTimeMillis();
        //耗时
        long costTime=end-begin;


        //构建日志对象
        OperateLog operateLog=new OperateLog();
        operateLog.setOperateEmpId(getCurrentUserId());//获取当前登录用户
        operateLog.setOperateTime(LocalDateTime.now());//获取 当前时间
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());// 获取 类名
        operateLog.setMethodName(joinPoint.getSignature().getName());// 获取 方法名
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));// 获取方法的 参数
        operateLog.setReturnValue(result.toString());
        operateLog.setCostTime(costTime);

        //插入日志
        operateLogMapper.insert(operateLog);
        return result;


    }
    private int getCurrentUserId() {
        return CurrentHolder.getCurrentId();
    }
}
